<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="所属楼栋">
              <a-select placeholder="请选择楼栋" v-model="queryParam.buildingId" allowClear @change="onBuildingChange">
                <a-select-option v-for="building in buildingList" :key="building.id" :value="building.id">
                  {{ building.buildingName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="房间编号">
              <a-input placeholder="请输入房间编号" v-model="queryParam.roomCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="楼层">
              <a-input-number placeholder="请输入楼层" v-model="queryParam.floor" :min="1"></a-input-number>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :md="6" :sm="8">
              <a-form-item label="状态">
                <a-select placeholder="请选择状态" v-model="queryParam.status" allowClear>
                  <a-select-option value="空闲">空闲</a-select-option>
                  <a-select-option value="已满">已满</a-select-option>
                  <a-select-option value="维修中">维修中</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('宿舍房间信息')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete" />删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域 -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <template slot="bedInfo" slot-scope="text, record">
          {{ record.usedBeds }}/{{ record.bedCount }}
        </template>

        <template slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-table>
    </div>

    <!-- 表单区域 -->
    <dormitory-room-modal ref="modalForm" @ok="modalFormOk"></dormitory-room-modal>
  </a-card>
</template>

<script>
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import DormitoryRoomModal from './modules/DormitoryRoomModal'
  import { getAction } from '@/api/manage'

  export default {
    name: "DormitoryRoomList",
    mixins: [JeecgListMixin],
    components: {
      DormitoryRoomModal
    },
    data() {
      return {
        description: '宿舍房间管理页面',
        // 查询条件
        queryParam: {},
        // 禁用mixin中的created自动加载
        disableMixinCreated: true,
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '所属楼栋',
            align: "center",
            dataIndex: 'buildingName'
          },
          {
            title: '房间编号',
            align: "center",
            dataIndex: 'roomCode'
          },
          {
            title: '楼层',
            align: "center",
            dataIndex: 'floor'
          },
          {
            title: '房间类型',
            align: "center",
            dataIndex: 'roomType'
          },
          {
            title: '床位使用',
            align: "center",
            scopedSlots: { customRender: 'bedInfo' }
          },
          {
            title: '状态',
            align: "center",
            dataIndex: 'status'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list: "/dormitory/room/list",
          delete: "/dormitory/room/delete",
          deleteBatch: "/dormitory/room/deleteBatch",
          exportXlsUrl: "/dormitory/room/exportXls",
          importExcelUrl: "/dormitory/room/importExcel",
        },
        buildingList: [],
      }
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    created() {
      // 先加载楼栋数据，再加载房间列表
      this.loadBuildingList().then(() => {
        this.loadData(1);
      });
    },
    methods: {
      // 初始化方法
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        this.loading = true;
        getAction(this.url.list, { ...this.queryParam, ...this.isorter, ...this.filters, pageNo: this.ipagination.current, pageSize: this.ipagination.pageSize }).then((res) => {
          if (res.success) {
            let records = res.result.records || [];
            // 处理楼栋名称
            if (records.length > 0 && this.buildingList.length > 0) {
              records.forEach(item => {
                if (item.buildingId && !item.buildingName) {
                  const building = this.buildingList.find(b => b.id === item.buildingId);
                  if (building) {
                    item.buildingName = building.buildingName;
                  }
                }
              });
            }
            this.dataSource = records;
            console.log('处理后的房间列表数据:', this.dataSource);
            this.ipagination.total = res.result.total || 0;
          } else {
            this.$message.warning(res.message || '加载房间列表失败');
          }
          this.loading = false;
        }).catch(err => {
          console.error('加载房间列表出错:', err);
          this.$message.error('加载房间列表出错');
          this.loading = false;
        })
      },
      // 加载楼栋列表
      loadBuildingList() {
        console.log('开始加载楼栋列表');
        return getAction("/dormitory/building/listAll").then(res => {
          console.log('楼栋列表返回结果:', res);
          if (res.success) {
            this.buildingList = res.result || [];
            console.log('楼栋列表数据:', this.buildingList);
          } else {
            this.$message.warning(res.message || '加载楼栋列表失败');
          }
          return Promise.resolve(this.buildingList);
        }).catch(err => {
          console.error('加载楼栋列表出错:', err);
          this.$message.error('加载楼栋列表出错');
          return Promise.reject(err);
        })
      },
      // 楼栋选择变更
      onBuildingChange(value) {
        this.searchQuery();
      },
      handleDetail(record) {
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title = "详情";
        this.$refs.modalForm.disableSubmit();
      }
    }
  }
</script> 